"""
Test Option A.2 Implementation: Write Matrix Fix and In-Memory Parity

This test verifies:
1. write_matrix() correctly writes data to disk with flush/sync
2. No UndefVarError from sync() call
3. Written data matches input data (no zeros corruption)
"""

using Test
using FLEXINVERT
using FLEXINVERT.Inversion: write_matrix
using DelimitedFiles
using LinearAlgebra: norm

@testset "Option A.2: Write Matrix Fix" begin

    @testset "Write Matrix Basic Functionality" begin
        # Create test matrix with known values
        test_mat = [1.0 2.0 3.0; 4.0 5.0 6.0; 7.0 8.0 9.0]
        test_path = joinpath(tempdir(), "test_write_matrix_$(time()).txt")

        # Test that write_matrix returns true and doesn't throw
        @test write_matrix(test_path, test_mat) === true

        # Verify file exists
        @test isfile(test_path)

        # Read back and verify content matches
        readback = readdlm(test_path)
        @test size(readback) == size(test_mat)
        @test readback ≈ test_mat

        # Clean up
        rm(test_path)
        @info "✅ Basic write_matrix test passed"
    end

    @testset "Write Matrix with Large Values (zwork-like)" begin
        # Test with values similar to zwork magnitudes (1e11)
        large_mat = randn(288, 5) .* 1e11
        test_path = joinpath(tempdir(), "test_large_matrix_$(time()).txt")

        # Write
        @test write_matrix(test_path, large_mat) === true

        # Read back
        readback = readdlm(test_path)

        # Verify no zeros corruption (max should be similar magnitude)
        @test maximum(abs.(readback)) > 1e10
        @test count(x -> abs(x) > 1e-10, readback) > 0
        @test size(readback) == size(large_mat)

        # Verify values match within write_matrix precision (%.8e format ~1e-8)
        rel_err = norm(readback - large_mat) / norm(large_mat)
        @test rel_err < 1e-7  # Account for %.8e formatting precision

        # Clean up
        rm(test_path)
        @info "✅ Large value write_matrix test passed" max_val=maximum(abs.(readback)) rel_error=rel_err
    end

    @testset "Write Matrix with Sparse Data (zwork pattern)" begin
        # Test with sparse pattern similar to actual zwork (710 non-zeros out of 1440)
        sparse_mat = zeros(288, 5)
        # Populate ~50% with non-zero values
        for i in 1:144
            for j in 1:5
                if rand() > 0.5
                    sparse_mat[i, j] = randn() * 1e11
                end
            end
        end

        test_path = joinpath(tempdir(), "test_sparse_matrix_$(time()).txt")

        n_nonzero_orig = count(x -> abs(x) > 1e-10, sparse_mat)
        @info "Testing sparse matrix" n_nonzero=n_nonzero_orig total=length(sparse_mat)

        # Write
        @test write_matrix(test_path, sparse_mat) === true

        # Read back
        readback = readdlm(test_path)

        # Verify sparsity pattern preserved
        n_nonzero_read = count(x -> abs(x) > 1e-10, readback)
        @test n_nonzero_read == n_nonzero_orig

        # Verify values match
        @test readback ≈ sparse_mat

        # Clean up
        rm(test_path)
        @info "✅ Sparse matrix write_matrix test passed" nonzero_preserved=n_nonzero_read
    end

    @testset "Write Matrix Persistence (sync verification)" begin
        # This test ensures data is actually synced to disk
        test_mat = randn(100, 10) .* 1e9
        test_path = joinpath(tempdir(), "test_sync_$(time()).txt")

        # Write
        write_matrix(test_path, test_mat)

        # Immediately read back without closing Julia session
        # If sync() is working, data should be on disk
        readback1 = readdlm(test_path)
        @test readback1 ≈ test_mat

        # Read again to verify persistence
        readback2 = readdlm(test_path)
        @test readback2 ≈ test_mat
        @test readback1 ≈ readback2

        # Clean up
        rm(test_path)
        @info "✅ Write persistence (sync) test passed"
    end

end

@info "All Option A.2 write_matrix tests completed successfully"
